package com.elitecrm.saas.service;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;

import com.elite.Saas.lib.system.ServletIn;


public abstract class AbstractService extends ServletIn{
	private static final Log log = LogFactory.getLog(AbstractService.class);
	private DataSource dataSource;
	public DataSource getDataSource() {
		return dataSource;
	}
	
	protected String checkUUID(String uuid){
		//OneStaff os = getOneStaffByKey(uuid);
		//dataSource = getOneDataSource(os, "");
		Document result = DocumentFactory.getInstance().createDocument("utf-8");
		Element root = result.addElement("R");
		root.addElement("result").addText("1");
		root.addElement("staff_id").addText("SELITE");
		root.addElement("ep_id").addText("A00001");
		return result.asXML();
	}
	@Override
	public String DoExec(String vPara,String vRemoteIP) {
		log.debug("Request by remote address "+vRemoteIP+" with param "+vPara);
		String result = "";
		try{
			result = callService(vPara);
		}catch(Exception e){
			if(e instanceof EliteSAASException){
				EliteSAASException saasExce = (EliteSAASException)e;
				result = generateErrorXMLReturn(saasExce.getErrorCode(),saasExce.getMessage());
			}else{
				result = generateErrorXMLReturn(e);
			}
		}
		log.debug("Return result: "+result);
		return result;
	}
	
	/**
		<R>
			<Result>-1</Result>
			<ErrCode>Error Code</ErrCode>
			<ErrDesc>Error Description</ErrorDesc>
		</R>
	**/
	protected String generateErrorXMLReturn(Integer errorCode, String errorMessage){
		Document errorDoc = DocumentFactory.getInstance().createDocument("utf-8");
		Element rootEle = (Element)errorDoc.addElement("R");
		rootEle.addElement("Result").addText("-1");
		rootEle.addElement("ErrCode").addText(""+errorCode);
		rootEle.addElement("ErrDesc").addText(errorMessage);
		return errorDoc.asXML();
	}
	protected String generateErrorXMLReturn(Exception e){
		return generateErrorXMLReturn(EliteSAASException.INTERNAL_ERROR, e.getMessage());
	}
	
	public abstract String callService(String param) throws Exception;
}
